package com.maibow.controller.admin;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.maibow.base.defines.ParameterReadService;
import com.maibow.controller.base.BaseController;
import com.maibow.entity.Page;
import com.maibow.service.admin.NewUserService;
import com.maibow.util.AppUtil;
import com.maibow.util.CommonConstants;
import com.maibow.util.PageData;
import com.maibow.util.SmsUtil;
import com.maibow.util.Tools;
import com.maibow.util.mail.SimpleMailSender;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.controller.system
 * 文件名：HeadController.java
 * 作者: 吴比(Wubi)
 * 时间：2015年4月2日-上午9:07:58
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
@Controller
@RequestMapping(value = "/newhead")
public class NewHeadController extends BaseController {

    @Resource(name = "newuserService")
    private NewUserService userService;
    
    @Resource(name = "parameterReadService")
    private ParameterReadService parameterReadService;

    /**
     * 获取头部信息
     */
    @RequestMapping(value = "/getOperatorName")
    @ResponseBody
    public Object getList() {
        PageData pageData = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            pageData = this.getPageData();
            List<PageData> pageDataList = new ArrayList<PageData>();

            // shiro管理的session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();

            PageData operatorPageDatas = new PageData();
            operatorPageDatas = (PageData) session.getAttribute(CommonConstants.SESSION_OPERATOR_PAGEDATAS);

            if (null == operatorPageDatas) {
                String username = session.getAttribute(CommonConstants.SESSION_OPERATOR_NAME).toString(); // 获取当前登录者loginname
                pageData.put("username", username);
                operatorPageDatas = userService.findOperatorByOperatorName(pageData);
                session.setAttribute(CommonConstants.SESSION_OPERATOR_PAGEDATAS, operatorPageDatas);
            }

            pageDataList.add(operatorPageDatas);
            map.put("list", pageDataList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pageData, map);
    }

    /**
     * 保存皮肤
     */
    @RequestMapping(value = "/setSkin")
    public void setSkin(PrintWriter out) {
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();

            // shiro管理的session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();

            String username = session.getAttribute(CommonConstants.SESSION_OPERATOR_NAME).toString();// 获取当前登录者loginname
            pageData.put("username", username);
            userService.setSkin(pageData);
            session.removeAttribute(CommonConstants.SESSION_OPERATOR_PAGEDATAS);
            session.removeAttribute(CommonConstants.SESSION_OPERATOR_ROLE);
            out.write("success");
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 去编辑邮箱页面
     */
    @RequestMapping(value = "/editEmail")
    public ModelAndView editEmail() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        mv.setViewName("system/head/edit_email");
        mv.addObject("pageData", pageData);
        return mv;
    }

    /**
     * 去发送短信页面
     */
    @RequestMapping(value = "/goSendSms")
    public ModelAndView goSendSms() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        mv.setViewName("system/head/send_sms");
        mv.addObject("pageData", pageData);
        return mv;
    }

    /**
     * 发送短信
     */
    @RequestMapping(value = "/sendSms")
    @ResponseBody
    public Object sendSms() {
        PageData pageData = new PageData();
        pageData = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "ok"; // 发送状态
        int count = 0; // 统计发送成功条数
        int zcount = 0; // 理论条数

        List<PageData> pageDataList = new ArrayList<PageData>();

        String PHONEs = pageData.getString("PHONE"); // 对方邮箱
        String CONTENT = pageData.getString("CONTENT"); // 内容
        String isAll = pageData.getString("isAll"); // 是否发送给全体成员
                                                    // yes
                                                    // or
                                                    // no
        String TYPE = pageData.getString("TYPE"); // 类型
                                                  // 1：短信接口1
                                                  // 2：短信接口2
        String fmsg = pageData.getString("fmsg"); // 判断是系统用户还是会员
                                                  // "appuser"为会员用户

        if ("yes".endsWith(isAll)) {
            try {
                List<PageData> userList = new ArrayList<PageData>();

                userList = userService.querUserPageWithoutRolePageData(pageData);

                zcount = userList.size();
                try {
                    for (int i = 0; i < userList.size(); i++) {
                        if (Tools.checkMobileNumber(userList.get(i).getString("PHONE"))) { // 手机号格式不对就跳过
                            if ("1".equals(TYPE)) {
                                SmsUtil.sendSms1(userList.get(i).getString("PHONE"), CONTENT); // 调用发短信函数1
                            } else {
                                SmsUtil.sendSms2(userList.get(i).getString("PHONE"), CONTENT); // 调用发短信函数2
                            }
                            count++;
                        } else {
                            continue;
                        }
                    }
                    msg = "ok";
                } catch (Exception e) {
                    msg = "error";
                }

            } catch (Exception e) {
                msg = "error";
            }
        } else {
            PHONEs = PHONEs.replaceAll("；", ";");
            PHONEs = PHONEs.replaceAll(" ", "");
            String[] arrTITLE = PHONEs.split(";");
            zcount = arrTITLE.length;
            try {
                for (int i = 0; i < arrTITLE.length; i++) {
                    if (Tools.checkMobileNumber(arrTITLE[i])) { // 手机号式不对就跳过
                        if ("1".equals(TYPE)) {
                            SmsUtil.sendSms1(arrTITLE[i], CONTENT); // 调用发短信函数1
                        } else {
                            SmsUtil.sendSms2(arrTITLE[i], CONTENT); // 调用发短信函数2
                        }
                        count++;
                    } else {
                        continue;
                    }
                }
                msg = "ok";
            } catch (Exception e) {
                msg = "error";
            }
        }
        pageData.put("msg", msg);
        pageData.put("count", count); // 成功数
        pageData.put("ecount", zcount - count); // 失败数
        pageDataList.add(pageData);
        map.put("list", pageDataList);
        return AppUtil.returnObject(pageData, map);
    }

    /**
     * 去发送电子邮件页面
     */
    @RequestMapping(value = "/goSendEmail")
    public ModelAndView goSendEmail() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        mv.setViewName("system/head/send_email");
        mv.addObject("pageData", pageData);
        return mv;
    }

    /**
     * 发送电子邮件
     */
    @RequestMapping(value = "/sendEmail")
    @ResponseBody
    public Object sendEmail() {
        PageData pageData = new PageData();
        pageData = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "ok"; // 发送状态
        int count = 0; // 统计发送成功条数
        int zcount = 0; // 理论条数

        String strEMAIL = Tools.readTxtFile(CommonConstants.EMAIL); // 读取邮件配置

        List<PageData> pageDataList = new ArrayList<PageData>();

        String toEMAIL = pageData.getString("EMAIL"); // 对方邮箱
        String TITLE = pageData.getString("TITLE"); // 标题
        String CONTENT = pageData.getString("CONTENT"); // 内容
        String TYPE = pageData.getString("TYPE"); // 类型
        String isAll = pageData.getString("isAll"); // 是否发送给全体成员
                                                    // yes
                                                    // or
                                                    // no

        String fmsg = pageData.getString("fmsg"); // 判断是系统用户还是会员
                                                  // "appuser"为会员用户

        if (null != strEMAIL && !"".equals(strEMAIL)) {
            String strEM[] = strEMAIL.split(",fh,");
            if (strEM.length == 4) {
                if ("yes".endsWith(isAll)) {
                    try {
                        List<PageData> userList = new ArrayList<PageData>();

                        userList = userService.querUserPageWithoutRolePageData(pageData);

                        zcount = userList.size();
                        try {
                            for (int i = 0; i < userList.size(); i++) {
                                if (Tools.checkEmail(userList.get(i).getString("EMAIL"))) { // 邮箱格式不对就跳过
                                    SimpleMailSender.sendEmail(strEM[0], strEM[1], strEM[2], strEM[3], userList.get(i).getString("EMAIL"), TITLE, CONTENT, TYPE);// 调用发送邮件函数
                                    count++;
                                } else {
                                    continue;
                                }
                            }
                            msg = "ok";
                        } catch (Exception e) {
                            msg = "error";
                        }

                    } catch (Exception e) {
                        msg = "error";
                    }
                } else {
                    toEMAIL = toEMAIL.replaceAll("；", ";");
                    toEMAIL = toEMAIL.replaceAll(" ", "");
                    String[] arrTITLE = toEMAIL.split(";");
                    zcount = arrTITLE.length;
                    try {
                        for (int i = 0; i < arrTITLE.length; i++) {
                            if (Tools.checkEmail(arrTITLE[i])) { // 邮箱格式不对就跳过
                                SimpleMailSender.sendEmail(strEM[0], strEM[1], strEM[2], strEM[3], arrTITLE[i], TITLE, CONTENT, TYPE);// 调用发送邮件函数
                                count++;
                            } else {
                                continue;
                            }
                        }
                        msg = "ok";
                    } catch (Exception e) {
                        msg = "error";
                    }
                }
            } else {
                msg = "error";
            }
        } else {
            msg = "error";
        }
        pageData.put("msg", msg);
        pageData.put("count", count); // 成功数
        pageData.put("ecount", zcount - count); // 失败数
        pageDataList.add(pageData);
        map.put("list", pageDataList);
        return AppUtil.returnObject(pageData, map);
    }

    /**
     * 去系统设置页面
     */
    @RequestMapping(value = "/goSystem")
    public ModelAndView goEditEmail() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        pageData.put("YSYNAME", Tools.readTxtFile(CommonConstants.SYSNAME)); // 读取系统名称
        pageData.put("COUNTPAGE", Tools.readTxtFile(CommonConstants.PAGE)); // 读取每页条数
        String strEMAIL = Tools.readTxtFile(CommonConstants.EMAIL); // 读取邮件配置
        String strSMS1 = Tools.readTxtFile(CommonConstants.SMS1); // 读取短信1配置
        String strSMS2 = Tools.readTxtFile(CommonConstants.SMS2); // 读取短信2配置

        if (null != strEMAIL && !"".equals(strEMAIL)) {
            String strEM[] = strEMAIL.split(",fh,");
            if (strEM.length == 4) {
                pageData.put("SMTP", strEM[0]);
                pageData.put("PORT", strEM[1]);
                pageData.put("EMAIL", strEM[2]);
                pageData.put("PAW", strEM[3]);
            }
        }

        if (null != strSMS1 && !"".equals(strSMS1)) {
            String strS1[] = strSMS1.split(",fh,");
            if (strS1.length == 2) {
                pageData.put("SMSU1", strS1[0]);
                pageData.put("SMSPAW1", strS1[1]);
            }
        }

        if (null != strSMS2 && !"".equals(strSMS2)) {
            String strS2[] = strSMS2.split(",fh,");
            if (strS2.length == 2) {
                pageData.put("SMSU2", strS2[0]);
                pageData.put("SMSPAW2", strS2[1]);
            }
        }

        mv.setViewName("system/head/sys_edit");
        mv.addObject("pageData", pageData);

        return mv;
    }

    /**
     * 保存系统设置
     */
    @RequestMapping(value = "/saveSys")
    public ModelAndView saveU(PrintWriter out) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        Tools.writeFile(CommonConstants.SYSNAME, pageData.getString("YSYNAME")); // 写入系统名称
        Tools.writeFile(CommonConstants.PAGE, pageData.getString("COUNTPAGE")); // 写入每页条数
        Tools.writeFile(CommonConstants.EMAIL, pageData.getString("SMTP") + ",fh," + pageData.getString("PORT") + ",fh," + pageData.getString("EMAIL") + ",fh," + pageData.getString("PAW")); // 写入邮件服务器配置
        Tools.writeFile(CommonConstants.SMS1, pageData.getString("SMSU1") + ",fh," + pageData.getString("SMSPAW1")); // 写入短信1配置
        Tools.writeFile(CommonConstants.SMS2, pageData.getString("SMSU2") + ",fh," + pageData.getString("SMSPAW2")); // 写入短信2配置
        mv.addObject("msg", "OK");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 去代码生成器页面
     */
    @RequestMapping(value = "/goProductCode")
    public ModelAndView goProductCode() throws Exception {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("system/head/productCode");
        return mv;
    }
    
    /**
     * 去 全局系统参数配置  页面
     */
    @RequestMapping(value = "/gosConfigure")
    public ModelAndView gosConfigure(Page page) throws Exception {
        ModelAndView mv = this.getModelAndView();
        
        PageData pageData = this.getPageData();
        page.setPageData(pageData);
        List<PageData> sconfigureList = parameterReadService.querSconfigureslistPageWithConfigureName(page);        
        mv.setViewName("system/define/define_list");
        mv.addObject("sconfigureList", sconfigureList);
        mv.addObject("pageData", pageData);
        mv.addObject("sConfigureName", "");
        return mv;
    }
    
    /**
     * 获得 合全局系统参数配置数据列表
     * @return
     */
    @RequestMapping(value = "/listsConfiguresData")
    public ModelAndView listsConfiguresData(Page page) {
    	
    	 ModelAndView modelView = this.getModelAndView();
         PageData pageData = this.getPageData();

         String sConfigureName = pageData.getString("sConfigureName");
         if(StringUtils.isBlank(sConfigureName)){
        	 sConfigureName="";
         }

         if (null != sConfigureName && !"".equals(sConfigureName)) {
        	 sConfigureName = sConfigureName.trim();
             pageData.put("sConfigureName", sConfigureName);
         }

         page.setPageData(pageData);

         List<PageData> sconfigureList = parameterReadService.querSconfigureslistPageWithConfigureName(page);
         
         modelView.setViewName("system/define/define_list");
         modelView.addObject("sconfigureList", sconfigureList);
         modelView.addObject("pageData", pageData);
         modelView.addObject("sConfigureName", sConfigureName);
         return modelView;
    }
    
    /**
	 * 去新增页面
	 */
	@RequestMapping(value="/toAddSconfigure")
	public ModelAndView toAddSconfigure(Page page){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			mv.setViewName("system/define/define_edit");
			mv.addObject("pd", pd);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return mv;
	}
    
    /**
	 * 去编辑页面
	 */
	@RequestMapping(value="/toEditSconfigure")
	public ModelAndView toEditSconfigure(String SCODE)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		if(parameterReadService.findCodeCount(pd) != null){
			mv.addObject("msg", "no");
		}else{
			mv.addObject("msg", "ok");
		}
		pd = parameterReadService.findByParams(pd);
		mv.setViewName("system/define/define_edit");
		mv.addObject("pd", pd);
		return mv;
	}
	
	/**
	 * 判断编码是否存在
	 */
	@RequestMapping(value="/sConfigureshas")
	public void has(PrintWriter out){
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(parameterReadService.findCodeCount(pd) != null){
				out.write("error");
			}else{
				out.write("success");
			}
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 保存
	 */
	@RequestMapping(value="/sConfiguresSave")
	public ModelAndView sConfiguresSave(PrintWriter out) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		String SCODE = pd.getString("SCODE");
		pd.put("SCODE", SCODE);
		
		String SNAME = pd.getString("SNAME");
		pd.put("SNAME", SNAME);
		
		String SVALUE = pd.getString("SVALUE");
		pd.put("SVALUE", SVALUE);
		
		String SSORT = pd.getString("SSORT");
		pd.put("SSORT", Integer.valueOf(SSORT));
		
		pd.put("SCLASS", Integer.valueOf(5));
		pd.put("SNODE", "0");
		
		
		
		if(parameterReadService.findCodeCount(pd) == null){
			parameterReadService.save(pd);
		}else{
			parameterReadService.edit(pd);
		}
		
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
		
	}
	
	/**
	 * 删除某项配制
	 */
	@RequestMapping(value="/toDelSconfigure")
	public void toDelSconfigure(PrintWriter out){
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			if(parameterReadService.findCodeCount(pd) == null){
				out.write("false");
			}else{
				parameterReadService.delete(pd);
				out.write("success");
			}
			
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}

}
